<template>
  <div class="personal-accounting">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>事务会计分析</h1>
      <p>基于事务库与个人事务的价值核算与可视化</p>
    </div>

    <!-- 用户选择 -->
    <div class="user-selector">
      <el-card>
        <template #header>
          <span>选择用户</span>
        </template>
        <el-select v-model="selectedUserId" placeholder="请选择用户" @change="loadUserData">
          <el-option
            v-for="user in users"
            :key="user.id"
            :label="user.realName || user.username"
            :value="user.id"
          />
        </el-select>
      </el-card>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-loading-directive v-loading="loading" text="加载中...">
        <div style="height: 200px;"></div>
      </el-loading-directive>
    </div>

    <!-- 主要内容区域 -->
    <div v-else-if="selectedUserId" class="main-content">
      <!-- 概览统计 -->
      <div class="overview-section">
        <h2>事务概览</h2>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon total-assets"><el-icon><TrendCharts /></el-icon></div>
                <div class="stat-info">
                  <h3>{{ formatNumber(stats.totalAssets) }}</h3>
                  <p>总资产（正向价值）</p>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon net-profit"><el-icon><TrendCharts /></el-icon></div>
                <div class="stat-info">
                  <h3>{{ formatNumber(stats.netValue) }}</h3>
                  <p>净价值（资产-负债）</p>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon efficiency"><el-icon><TrendCharts /></el-icon></div>
                <div class="stat-info">
                  <h3>{{ formatPercent(stats.efficiencyIndex) }}</h3>
                  <p>事务效率指数（值/时长）</p>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="stat-card">
              <div class="stat-content">
                <div class="stat-icon roi"><el-icon><TrendCharts /></el-icon></div>
                <div class="stat-info">
                  <h3>{{ formatPercent(stats.roi) }}</h3>
                  <p>投入产出率（资产/负债）</p>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 类别分布与趋势图表 -->
      <div class="charts-section">
        <h2>可视化分析</h2>
        <PersonalCharts
          :category-values="categoryValues"
          :rating-counts="ratingCounts"
          :daily-net-series="dailyNetSeries"
        />
      </div>

      <!-- 财务报表（简版） -->
      <div class="financial-section">
        <h2>事务财务报表</h2>
        <el-card>
          <el-tabs v-model="activeTab">
            <el-tab-pane label="资产负债表" name="balance">
              <div class="financial-table">
                <h3>资产负债表</h3>
                <el-table :data="balanceSheetData" style="width: 100%">
                  <el-table-column prop="item" label="项目" width="200" />
                  <el-table-column prop="amount" label="金额" width="150">
                    <template #default="scope">
                      {{ formatNumber(scope.row.amount) }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
            <el-tab-pane label="损益表" name="income">
              <div class="financial-table">
                <h3>损益表</h3>
                <el-table :data="incomeStatementData" style="width: 100%">
                  <el-table-column prop="item" label="项目" width="200" />
                  <el-table-column prop="amount" label="金额" width="150">
                    <template #default="scope">
                      {{ formatNumber(scope.row.amount) }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { TrendCharts } from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import { personalApi } from '@/api/personal'
import { catalogApi } from '@/api/catalog'
import PersonalCharts from '@/components/personal/PersonalCharts.vue'

export default {
  name: 'PersonalAccounting',
  components: { TrendCharts, PersonalCharts },
  setup() {
    const users = ref([])
    const selectedUserId = ref(null)
    const loading = ref(false)
    const activeTab = ref('balance')

    const stats = reactive({
      totalAssets: 0,
      totalLiabilities: 0,
      netValue: 0,
      efficiencyIndex: 0,
      roi: 0
    })

    const categoryValues = ref([]) // [{ name, value }]
    const ratingCounts = ref([])   // [{ rating, count }]
    const dailyNetSeries = ref([]) // [{ date, value }]

    const balanceSheetData = ref([])
    const incomeStatementData = ref([])

    const ratingWeight = { 1: 0.6, 2: 0.8, 3: 1.0, 4: 1.2, 5: 1.4 }
    const categoryWeight = { 1: 1.0, 2: 1.3, 3: 0.8, 4: 1.1 }
    const itemWeightOverrides = {
      '锻炼': 1.2,
      '用餐': 0.6,
      '睡觉': 0.5,
      '喝酒': -1.2,
      '开车': 0.7
    }

    const formatNumber = (n) => {
      if (!Number.isFinite(n)) return '0.00'
      return Number(n).toFixed(2)
    }
    const formatPercent = (n) => {
      if (!Number.isFinite(n)) return '0.00%'
      return `${(Number(n) * 100).toFixed(2)}%`
    }

    const fetchUsers = async () => {
      const res = await userApi.getUsers()
      users.value = res.data.data || []
      if (users.value.length > 0) {
        selectedUserId.value = users.value[0].id
        await loadUserData(selectedUserId.value)
      }
    }

    const loadUserData = async (uid) => {
      if (!uid) return
      loading.value = true
      try {
        const [affairRes, catalogRes] = await Promise.all([
          personalApi.affairs.getAffairs(uid),
          catalogApi.getItems()
        ])
        const affairs = affairRes.data.data || []
        const catalog = catalogRes.data || catalogRes.data.data || []
        aggregateAffairs(affairs, catalog)
      } catch (e) {
        console.error('加载事务数据失败', e)
      } finally {
        loading.value = false
      }
    }

    const parseCategoryCode = (affairCode) => {
      // 形如 AFF-3-2-20250101-001
      const m = /^AFF-(\d+)-/.exec(affairCode || '')
      return m ? Number(m[1]) : null
    }

    const getCategoryNameByCode = (catalog, categoryCode) => {
      const item = (catalog || []).find(x => x.categoryCode === categoryCode)
      return item ? item.categoryName : `类别${categoryCode}`
    }

    const aggregateAffairs = (affairs, catalog) => {
      let totalAssets = 0
      let totalLiabilities = 0
      let totalValue = 0
      let totalHours = 0
      const categoryMap = new Map() // name -> value
      const ratingMap = new Map()   // rating -> count
      const dailyMap = new Map()    // date -> net value

      for (const a of affairs) {
        const start = new Date(a.startDate)
        const end = new Date(a.endDate)
        const hours = Math.max(0, (end - start) / 3600000)
        const rating = Number(a.completionRating || 3)
        const catCode = parseCategoryCode(a.affairCode)
        const catName = getCategoryNameByCode(catalog, catCode)

        const rw = ratingWeight[rating] ?? 1.0
        const cw = categoryWeight[catCode] ?? 1.0
        const iw = itemWeightOverrides[a.affairName] ?? 1.0
        const value = hours * rw * cw * iw

        totalHours += hours
        totalValue += value
        if (value >= 0) totalAssets += value; else totalLiabilities += Math.abs(value)

        // 类别聚合（仅正向价值用于资产贡献饼图）
        const prev = categoryMap.get(catName) || 0
        categoryMap.set(catName, prev + Math.max(0, value))

        // 评级计数
        ratingMap.set(rating, (ratingMap.get(rating) || 0) + 1)

        // 每日净值
        const dateKey = (a.startDate || '').substring(0, 10)
        dailyMap.set(dateKey, (dailyMap.get(dateKey) || 0) + value)
      }

      // 概览指标
      stats.totalAssets = totalAssets
      stats.totalLiabilities = totalLiabilities
      stats.netValue = totalAssets - totalLiabilities
      stats.efficiencyIndex = totalHours > 0 ? (totalValue / totalHours) : 0
      stats.roi = totalLiabilities > 0 ? (totalAssets / totalLiabilities) : 0

      // 可视化数据
      categoryValues.value = Array.from(categoryMap.entries()).map(([name, value]) => ({ name, value }))
      ratingCounts.value = Array.from(ratingMap.entries()).sort((a,b)=>a[0]-b[0]).map(([rating, count]) => ({ rating, count }))
      dailyNetSeries.value = Array.from(dailyMap.entries()).sort((a,b)=>a[0].localeCompare(b[0])).map(([date, value]) => ({ date, value }))

      // 报表数据
      balanceSheetData.value = [
        { item: '总资产', amount: totalAssets },
        { item: '总负债', amount: totalLiabilities },
        { item: '所有者权益（净值）', amount: stats.netValue }
      ]
      incomeStatementData.value = [
        { item: '事务总产出（值）', amount: totalValue },
        { item: '事务总投入（小时）', amount: totalHours }
      ]
    }

    onMounted(async () => {
      await fetchUsers()
    })

    return {
      users,
      selectedUserId,
      loading,
      activeTab,
      stats,
      categoryValues,
      ratingCounts,
      dailyNetSeries,
      balanceSheetData,
      incomeStatementData,
      loadUserData,
      formatNumber,
      formatPercent
    }
  }
}
</script>

<style scoped>
.personal-accounting { padding: 20px; max-width: 1200px; margin: 0 auto; }
.page-header { text-align: center; margin-bottom: 30px; }
.page-header h1 { margin: 0 0 10px 0; color: #333; font-size: 28px; }
.page-header p { margin: 0; color: #666; font-size: 16px; }
.user-selector { margin-bottom: 30px; }
.main-content { margin-top: 20px; }
.overview-section, .charts-section, .financial-section { margin-bottom: 30px; }
.overview-section h2, .charts-section h2, .financial-section h2 { margin: 0 0 20px 0; color: #333; font-size: 20px; border-bottom: 2px solid #409eff; padding-bottom: 10px; }
.stat-card { margin-bottom: 20px; }
.stat-content { display: flex; align-items: center; }
.stat-icon { width: 60px; height: 60px; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-right: 15px; font-size: 24px; color: white; }
.stat-icon.total-assets { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.stat-icon.net-profit { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.stat-icon.efficiency { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.stat-icon.roi { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
.stat-info h3 { margin: 0; font-size: 20px; font-weight: bold; color: #333; }
.stat-info p { margin: 5px 0 0 0; color: #666; font-size: 14px; }
.financial-table h3 { margin: 0 0 20px 0; color: #333; font-size: 18px; }
.loading-container { text-align: center; padding: 50px; }
</style>